package com.sparrow.socket.util;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

public class CodecUtil {

    private static final ConcurrentHashMap<Class<?>, Object> codecClassCache = new ConcurrentHashMap<>();

    public static Object getCodec(Class<?> clazz) {
        return codecClassCache.computeIfAbsent(clazz, k -> {
            String fullClassName = ProtobufProxy.getFullClassName(clazz);
            try {
                return Class.forName(fullClassName).newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    public static <T> byte[] encode(T msg) {
        Codec<T> codec = (Codec<T>) getCodec(msg.getClass());
        try {
            return codec.encode(msg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T decode(Class<T> clazz, byte[] bytes) {
        Codec<T> codec = (Codec<T>) CodecUtil.getCodec(clazz);
        try {
            return codec.decode(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
